<?php

namespace App\Http\Controllers\Api\Alipay;

use GuzzleHttp\Client;

use Illuminate\Http\Request;

use App\Models\ConfigureFunction; //获取配置类

use App\Service\AlipayRsaService; //rsa签名类

use App\Http\Controllers\Controller;

class AlipayRequestController extends Controller
{

    const  gateway = 'https://openapi.alipaydev.com/gateway.do';  //支付宝请求地址

    private $app_id; //应用ID

    private $method; //接口名称

    private $biz_content; //请求参数的集合
    
    private $request_method = 'post'; // 请求方式

    private $response_key = ''; //支付宝接口相应的key

    public function __construct()
    {

        //查询支付宝APPID
        $config_obj = new ConfigureFunction();
        $this->app_id = $config_obj->getConfigureField(42, 'app_id');

    }

    /**
     * 支付宝请求
     * @return array
     */
    private function request()
    {

        $client = new Client();

        $http_data = [
            'app_id' => '2016081900289735',
            'method' => $this->method,
            'format' => 'JSON',
            'charset' => 'UTF-8',
            'sign_type' => 'RSA2',
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0',
        ];

        if (in_array($this->method, ['alipay.offline.material.image.upload'])) {
            $http_data = array_merge($http_data, $this->biz_content);
        } else {
            $http_data['biz_content'] = \GuzzleHttp\json_encode($this->biz_content, true);
        }
        $http_data['sign'] = AlipayRsaService::rsaSign( $http_data );

        error_log('支付宝请求参数：' . var_export($http_data,true));

        $requestUrl = self ::gateway . "?";
        foreach ($http_data as $sysParamKey => $sysParamValue) {
            $requestUrl .= "$sysParamKey="  . urlencode($this->characet($http_data)) . "&";
        }
        $requestUrl = substr($requestUrl, 0, -1);

        error_log('http参数：' .  var_export($requestUrl,true));

        if ( $this->request_method != 'get' ) {
            $request = $client->get($requestUrl, [
                'verify' => false,
                'query' => $http_data,
            ]);

        } else {
            $request = $client->post($requestUrl, [
                'verify' => false,
                'multipart' => [
                    [
                        'name' => 'image_content',
                        'contents' => fopen(ltrim($http_data['image_content'],'@'), 'b'),
                    ]
                ]
            ]);
        }

        error_log('http参数：' .  var_export(ltrim($http_data['image_content'],'@'),true));

        if ( $request->getStatusCode() != 200) {
            return ['code' => $request->getStatusCode(), 'message' => '请求失败'];
        }
        error_log('支付宝请求结果：' . $request->getBody()->getContents());

        $return_data = json_decode($request->getBody()->getContents());
        if (!$return_data) {
            return ['code' => 404, 'message' => '没有响应参数'];
        }
        error_log('支付宝请求结果：' . var_export($return_data,true));

        return ['code' => 200, 'message' => 'ok' , 'data' => $return_data[$this->response_key]];

    }


    /**
     * 会员卡模板创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function cardTemplateCreate(Request $request)
    {

        $biz_content = $request->input('biz_content');

        if ( empty($biz_content) ) {
            return response()->json(['code' => 100001, 'message' => '请求参数不能为空' ]);
        }

        $this->method = 'alipay.marketing.card.template.create';
        $this->biz_content = $biz_content['biz_content'];

        return response()->json( $this->request() );
    }

    /**
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function materialImageUpload(Request $request)
    {

        $image_type = $request->input('image_type');
        $image_name = $request->input('image_name', '1.jpg');
        $image_content = $request->input('image_content');

        if (empty($image_type)) {
            return response()->json(['code' => 100001, 'message' => '图片/视频格式不能为空' ]);
        }
        if (empty($image_name)) {
            return response()->json(['code' => 100002, 'message' => '图片/视频名称不能为空' ]);
        }
        if (empty($image_content)) {
            return response()->json(['code' => 100003, 'message' => '图片/视频地址不能为空' ]);
        }

        $this->method = 'alipay.offline.material.image.upload';
        $this->biz_content = [
            'image_type' => $image_type,
            'image_name' => $image_name,
            'image_content' => '@' . $image_content,
        ];
        $this->response_key = 'alipay_offline_material_image_upload_response';

        return response()->json( $this->request() );

    }

    private function characet($data, $targetCharset) {

        if (!empty($data)) {
            if (strcasecmp('UTF-8', $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, 'UTF-8');
            }
        }
        return $data;
    }


}